/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Validation;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**

 @author jtanguay
 */
@FacesConverter("convertInt")
public class IntConverter implements Converter{
    private FacesMessage fMsg = null;
    int valeurRecuperer;
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value){
        
        valeurRecuperer = 0;
        
	try {
            valeurRecuperer = Integer.parseInt(value);
            
        }catch (Exception e) {         
            if (e.getClass() == NumberFormatException.class || value.isEmpty()){
                        
                fMsg = new FacesMessage("The age must be a number.");
                fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
                
                throw new ConverterException(fMsg);	
            }	
	}  
        
        if (valeurRecuperer < 0){ 
                            
            fMsg = new FacesMessage("Your age can't be negative.");
            fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
            
            throw new ConverterException(fMsg);       
        }
        
	return valeurRecuperer;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
       return value.toString();

    }
    
}
